<template>
  <div class="upload">
    <el-upload
      v-model:file-list="defaultFileList"
      :accept="accept"
      :auto-upload="false"
      :before-remove="handleBeforeRemove"
      :disabled="!editable"
      :limit="limit"
      :multiple="false"
      :on-change="handleChange"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
    >
      <el-button v-show="editable" :icon="Upload" size="small" type="primary"> 选择文件 </el-button>

      <template #file="{ file }">
        <div>
          <ul class="el-upload-list el-upload-list--text">
            <li class="el-upload-list__item is-success" tabindex="0">
              <div class="el-upload-list__item-info">
                <a class="el-upload-list__item-name">
                  <i class="el-icon el-icon--document"></i>
                  <span class="el-upload-list__item-file-name">
                    {{ file.name }}
                  </span>
                </a>
              </div>
              <label style="position: absolute; top: 0; right: 5px">
                <el-button v-if="file.raw == null" :icon="Download" plain size="small" @click="handleDownload(file)" />
                <el-button v-show="editable" :icon="Delete" plain size="small" @click="handleRemove(file)" />
              </label>
            </li>
          </ul>
        </div>
      </template>
    </el-upload>
    <el-button v-show="!autoupload && editable" class="ml-3" type="success" @click="handleUpload"> 上传 </el-button>
  </div>
</template>

<script>
// import {} from 'element-plus'
import { ElMessageBox, ElLoading } from "element-plus";
import { Delete, Download, Upload } from "@element-plus/icons-vue";
import { deleteOne, downloadAttachment, uploadUrl, postRequest } from "@/api/mains";
import { succMsg, failMsg, confirm } from "@/utils/MessageUtils";

export default defineComponent({
  name: "UploadEmbed",
  components: {},
  props: {
    accept: {
      type: String,
      default: ""
    },
    limit: {
      type: Number,
      default: 1
    },
    autoupload: {
      type: Boolean,
      default: true
    },
    autoremove: {
      type: Boolean,
      default: true
    },
    editable: {
      type: Boolean,
      default: true
    },
    bid: {
      type: String,
      default: ""
    },
    btype: {
      type: String,
      default: ""
    },
    bclass: {
      type: String,
      default: ""
    }
  },
  emits: {
    callbackupload: null
  },
  setup(props, { emit }) {
    const state = reactive({
      loading: false,
      title: "上传",
      fileList: [],
      defaultFileList: [],
      delFileList: [],
      limit: "1",
      accept: "",
      autoupload: true,
      autoremove: true,
      editable: true,
      bid: "",
      btype: "",
      bclass: ""
    });
    state.accept = ref(props.accept);
    state.limit = ref(props.limit);
    state.autoupload = ref(props.autoupload);
    state.autoremove = ref(props.autoremove);
    state.editable = ref(props.editable);

    state.bid = ref(props.bid);
    state.btype = ref(props.btype);
    state.bclass = ref(props.bclass);

    const handleChange = file => {
      if (state.autoupload) {
        state.fileList = [];
        state.fileList.push(file);
        handleUpload();
      } else {
        state.fileList.push(file);
      }
    };

    const handleBeforeRemove = () => {
      return ElMessageBox.confirm(`确定要删除该附件吗?`).then(
        () => true,
        () => false
      );
    };
    const handleRemove = async file => {
      const newDefaultFile = [];
      state.defaultFileList.forEach(f => {
        if (f.uid != file.uid) {
          newDefaultFile.push(f);
        }
      });
      state.defaultFileList = newDefaultFile;

      if (file.raw == null) {
        state.delFileList.push(file);
        if (state.autoremove) {
          const responseData = await deleteOne("system/attachment", file.id);
          if (responseData.code == 200) {
            succMsg(responseData.msg);
          } else {
            failMsg(responseData.msg);
          }
        } else {
          state.delFileList.push(file);
        }
      }
      const newFile = [];
      state.fileList.forEach(f => {
        if (f.uid != file.uid) {
          if (f.raw != null) {
            newFile.push(f);
          }
        }
      });
      state.fileList = newFile;
    };

    const handleExceed = files => {
      if (state.limit == 1) {
        //替换当前的文件
        state.fileList = [];
        state.fileList.push(files[0]);
      } else {
        failMsg(
          `当前限制选择 ${state.limit} 个文件，本次选择了
                ${files.length}
                个文件`
        );
      }
    };

    const getFileList = () => {
      return { fileList: state.fileList, delList: state.delFileList };
    };

    const handleUpload = async () => {
      state.loading = true;
      if (state.fileList.length === 0) {
        failMsg("请选取文件");
        state.loading = false;
        return;
      } else {
        const loading = ElLoading.service({
          lock: true,
          text: "导入中，请稍候...",
          background: "rgba(0, 0, 0, 0.7)"
        });
        const formdata = new FormData();
        state.fileList.forEach(file => {
          console.log(file);
          formdata.append("files", file.raw);
        });
        formdata.append("bid", state.bid);
        formdata.append("btype", state.btype);
        formdata.append("bclass", state.bclass);

        const responseData = await uploadUrl("system/attachment", formdata);
        if (responseData.code == 200) {
          succMsg(responseData.msg);
        } else {
          failMsg(responseData.msg);
        }
        state.fileList = [];
        emit("callbackupload", responseData);
        state.loading = false;
        loading.close();
      }
    };

    const handlePreview = async file => {
      console.log(file);
    };

    const handleDownload = file => {
      confirm("你确定要下载此文件吗", async () => {
        const attachmentId = file.id;
        if (attachmentId != null && attachmentId != "") {
          downloadAttachment(attachmentId)
            .then(res => {
              const link = document.createElement("a");

              const blob = new Blob([res], {
                type: "application/octer-stream"
              });

              link.style.display = "none";

              link.href = URL.createObjectURL(blob);

              link.setAttribute("download", file.name);

              document.body.appendChild(link);

              link.click();

              document.body.removeChild(link);
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          failMsg("文件路径不存在");
        }
      });
    };

    onMounted(async () => {
      const responseData = await postRequest("system/attachment/query", {
        bid: state.bid,
        btype: state.btype,
        bclass: state.bclass
      });
      const oldList = [];
      const datas = responseData.data;
      if (datas != null && datas.length > 0) {
        for (let i = 0; i < datas.length; i++) {
          oldList.push({
            id: datas[i].id,
            name: datas[i].filename,
            url: datas[i].filepath
          });
        }
      }
      state.defaultFileList = oldList;
    });

    return {
      ...toRefs(state),
      getFileList,
      handleChange,
      handleExceed,
      handleRemove,
      handleDownload,
      handleBeforeRemove,
      handleUpload,
      handlePreview,
      Delete,
      Download,
      Upload
    };
  }
});
</script>

<style lang="scss" scoped>
.upload {
  .upload-content {
    .el-upload__tip {
      display: block;
      height: 30px;
      line-height: 30px;
    }
    :deep() {
      .el-upload--picture-card {
        width: 128px;
        height: 128px;
        margin: 3px 8px 8px;
        border: 2px dashed #c0ccda;
      }
      .el-upload-list--picture {
        margin-bottom: 20px;
      }
      .el-upload-list--picture-card {
        .el-upload-list__item {
          width: 128px;
          height: 128px;
          margin: 3px 8px 8px;
        }
      }
    }
  }
}
.text-left {
  padding-left: 30px;
  text-align: left;
}
h3 {
  padding-bottom: 20px;
}
.cust_btn30 {
  padding-top: 30px;
  padding-bottom: 60px;
}
.text_fise {
  font-size: 16px;
}
.text_fise > div {
  padding-bottom: 20px;
}
</style>
